/*
  Author: Ionel Crisu - crisuionel@yahoo.com
  support@FlashExtended.com
*/
package com.flashextended.utils.server.assetloader
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	
	import mx.controls.Alert;
	import mx.managers.CursorManager;

	public class LoadExternalAsset extends EventDispatcher
	{
		private var locationURL:String;
		private var loader:Loader;
		private var urlRequest:URLRequest;
		private var callBack:Function;
				
		public function LoadExternalAsset(locationURL:String, callBack:Function)
		{
			this.callBack = callBack;
			this.locationURL = locationURL;
			this.loader = new Loader();
			urlRequest = new URLRequest(locationURL);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, assetLoaded);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, dispatchIOError);			
		}
		
		private var _isBusyCursor:Boolean = true;
		public function set isBusyCursor(val:Boolean):void
		{
			_isBusyCursor = val;
		}
		public function get isBusyCursor():Boolean
		{
			return _isBusyCursor;
		}		
		
		public function start():void
		{
			try{
			loader.load(urlRequest);
			(isBusyCursor)?CursorManager.setBusyCursor():null;
			}catch(e:Error)
			{
				CursorManager.removeBusyCursor();
				trace("Error at LoadExternalAsset.as");
			}
		}
		
		private function assetLoaded(e:Event):void
		{
			//asset loaded
			//inform parent class about loaded content
			CursorManager.removeBusyCursor();
			this.dispatchEvent(new Event("asset_loaded"));
			try{
				callBack(loader);
			}catch(e:Error)
			{
				Alert.show("message-713130-"+e.message);
			}
		}
		private function dispatchIOError(e:IOErrorEvent):void
		{
			CursorManager.removeBusyCursor();
			this.dispatchEvent(new Event("IO_Error"));
			Alert.show("IOError! at LoadExternalAsset.as -78237482");
		}
		
		public function set asset(l:Loader):void
		{
			loader = l
		}
		public function get asset():Loader
		{
			return loader;
		}		
		
	}
}